/**
 * pharma-message - 27 févr. 2011 guillaume
 */
package org.bspv.pharma.message.mail.impl;

import java.util.Map.Entry;

import javax.mail.internet.MimeMessage;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.bspv.pharma.common.exception.TechnicalException;
import org.bspv.pharma.message.mail.MailTechnicalService;
import org.bspv.pharma.message.template.TemplateTechnicalService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

/**
 * Implémentation du service d'envoi de mail.
 * 
 * @author guillaume
 * 
 */
@Service(value = "mailService")
public class MailTechnicalServiceImpl implements MailTechnicalService {

    /**
     * LOGGER.
     */
    private static final Log LOGGER = LogFactory.getLog(MailTechnicalServiceImpl.class);

    /**
     * Mail sender.
     */
    @Autowired(required = true)
    private JavaMailSender mailSender;

    /**
     * 
     */
    @Autowired(required = true)
    private TemplateTechnicalService templateTechnicalService;

    /**
     * {@inheritDoc}
     */
    @Override
    @Async
    public void sendMail(final SimpleMail mail) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(mail.getFrom());
        message.setTo(mail.getTo());
        message.setSubject(mail.getSubject());
        message.setText(mail.getBody());
        mailSender.send(message);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @Async
    public void sendMail(final TemplatedMail mail) {
        try {
            MimeMessagePreparator preparator = new MimeMessagePreparator() {
                public void prepare(MimeMessage mimeMessage) throws Exception {
                    mimeMessage.addHeader("Content-Transfer-Encoding", "8bit");
                    // Création du message
                    boolean multipart = mail.getAttachments() != null && mail.getAttachments().size() > 0;
                    MimeMessageHelper message = new MimeMessageHelper(mimeMessage, multipart);
                    message.setTo(mail.getTo());
                    message.setFrom(mail.getFrom());
                    message.setSubject(mail.getSubject());
                    // Construction du corps du message à partir du template Velocity
                    String text = templateTechnicalService.generateTextContent(mail.getTemplate().getPath(),
                            mail.getDataModel());
                    message.setText(text, mail.isHtml());
                    // Ajout des pièces jointes
                    for (Entry<String, Resource> entry : mail.getAttachments().entrySet()) {
                        message.addAttachment(entry.getKey(), entry.getValue());
                    }
                }
            };
            this.mailSender.send(preparator);
        } catch (MailException m) {
            String msgHeader = "Erreur lors de l'envoi du mail";
            StringBuilder msg = new StringBuilder();
            msg.append(msgHeader).append(" : ").append(m.getMessage());
            LOGGER.error(msg.toString());
            throw new TechnicalException(msgHeader, m);
        }
    }

    /**
     * @param mailSender
     *            the mailSender to set
     */
    public void setMailSender(JavaMailSender mailSender) {
        this.mailSender = mailSender;
    }

    /**
     * @param templateTechnicalService
     *            the templateTechnicalService to set
     */
    public final void setTemplateTechnicalService(TemplateTechnicalService templateTechnicalService) {
        this.templateTechnicalService = templateTechnicalService;
    }
}
